#include "getliveinfohelper.h"
#include "liveinfoview.h"
#include "liveviewmanager.h"

GetLiveInfoHelper::GetLiveInfoHelper(LiveViewManager* view_mgr, QObject* parent)
    : QObject { parent }, view_mgr_(view_mgr)
{
}

int GetLiveInfoHelper::get(int platform, const QString& presenter_platform_id,
                           const LiveHandler& handler)
{
    static int id = 0;
    requests_.push_back(Request { ++id, platform, presenter_platform_id, handler,
                                  QDateTime::currentDateTime() });
    startNextRequest();
    return id;
}

void GetLiveInfoHelper::cancel(int id)
{
    for (auto it = requests_.constBegin(), end = requests_.constEnd(); it != end; ++it) {
        if ((*it).id == id) {
            requests_.erase(it);
            return;
        }
    }
    for (auto it = currents_.constBegin(), end = currents_.constEnd(); it != end; ++it) {
        if ((*it).id == id) {
            auto req = *it;
            currents_.erase(it);
            if (req.view) {
                req.view->unload();
            }
            startNextRequest();
            return;
        }
    }
}

void GetLiveInfoHelper::onGetLiveInfo(int presenter, const QString& args)
{
    for (auto it = currents_.constBegin(), end = currents_.constEnd(); it != end; ++it) {
        if ((*it).id == presenter) {
            auto req = *it;
            currents_.erase(it);
            req.handler(presenter, args);
            break;
        }
    }

    // 延迟10s，太频繁了，直播平台会禁止访问
    QTimer::singleShot(10000, this, &GetLiveInfoHelper::startNextRequest);
}

void GetLiveInfoHelper::startNextRequest()
{
    if (!requests_.empty()) {
        LiveInfoView* view = nullptr;
        const auto& views = view_mgr_->infoViews();
        for (auto p : views) {
            if (p->handled()) {
                view = p;
                break;
            }
        }
        if (view) {
            while (!requests_.empty()) {
                auto req = requests_.takeFirst();
                if (req.handler) {
                    req.view = view;
                    currents_.push_back(req);
                    view->getLiveInfo(req.id, req.platform, req.presenter_platform_id, 10000,
                                      LiveHandler(this, &GetLiveInfoHelper::onGetLiveInfo));
                    break;
                }
            }
        }
    } else {
        const auto& views = view_mgr_->infoViews();
        for (auto p : views) {
            if (p->handled()) {
                p->unload();
            }
        }
    }
}
